<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.json"};
  </script>

  <meta name="description" content="​    这里开始分析枚举过程的第一个来回，文章中会具体分析MM32F103相关的USB寄存器含义以及代码，从而更加直观的理解这个过程。 ​    枚举过程的第一个来回会发起第一个控制传输：  建立过程：主机 SETUP 包（发往地址 0 端点 0 ），主机数据包（请求设备描述符），设备握手包ACK。 数据过程：主机先发一个 IN 令牌包，设备发一个数据包，主机发 ACK 包。 状态过程：主机发">
<meta property="og:type" content="article">
<meta property="og:title" content="MM32F103上分析usb的枚举过程一">
<meta property="og:url" content="http://example.com/2021/05/12/MM32F103%E4%B8%8A%E5%88%86%E6%9E%90usb%E7%9A%84%E6%9E%9A%E4%B8%BE%E8%BF%87%E7%A8%8B%E4%B8%80/index.html">
<meta property="og:site_name" content="学无止境">
<meta property="og:description" content="​    这里开始分析枚举过程的第一个来回，文章中会具体分析MM32F103相关的USB寄存器含义以及代码，从而更加直观的理解这个过程。 ​    枚举过程的第一个来回会发起第一个控制传输：  建立过程：主机 SETUP 包（发往地址 0 端点 0 ），主机数据包（请求设备描述符），设备握手包ACK。 数据过程：主机先发一个 IN 令牌包，设备发一个数据包，主机发 ACK 包。 状态过程：主机发">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210427104212.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210427104326.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/%E5%BE%AE%E4%BF%A1%E6%88%AA%E5%9B%BE_20210427111337.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210427105459.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210427160420.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210427161355.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210506182948.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210506183958.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/%E5%BE%AE%E4%BF%A1%E6%88%AA%E5%9B%BE_20210509135027.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210509140654.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210509140822.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210510171243.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210510152813.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210512144107.png">
<meta property="article:published_time" content="2021-05-12T06:44:14.000Z">
<meta property="article:modified_time" content="2021-05-12T06:44:14.000Z">
<meta property="article:author" content="xudonglei">
<meta property="article:tag" content="USB基础">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210427104212.png">

<link rel="canonical" href="http://example.com/2021/05/12/MM32F103%E4%B8%8A%E5%88%86%E6%9E%90usb%E7%9A%84%E6%9E%9A%E4%B8%BE%E8%BF%87%E7%A8%8B%E4%B8%80/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>MM32F103上分析usb的枚举过程一 | 学无止境</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">学无止境</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Do not bb, show me the example</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/05/12/MM32F103%E4%B8%8A%E5%88%86%E6%9E%90usb%E7%9A%84%E6%9E%9A%E4%B8%BE%E8%BF%87%E7%A8%8B%E4%B8%80/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="xudonglei">
      <meta itemprop="description" content="搬砖 嵌入式">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学无止境">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          MM32F103上分析usb的枚举过程一
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-05-12 14:44:14" itemprop="dateCreated datePublished" datetime="2021-05-12T14:44:14+08:00">2021-05-12</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F/" itemprop="url" rel="index"><span itemprop="name">嵌入式</span></a>
                </span>
            </span>

          
            <span id="/2021/05/12/MM32F103%E4%B8%8A%E5%88%86%E6%9E%90usb%E7%9A%84%E6%9E%9A%E4%B8%BE%E8%BF%87%E7%A8%8B%E4%B8%80/" class="post-meta-item leancloud_visitors" data-flag-title="MM32F103上分析usb的枚举过程一" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2021/05/12/MM32F103%E4%B8%8A%E5%88%86%E6%9E%90usb%E7%9A%84%E6%9E%9A%E4%B8%BE%E8%BF%87%E7%A8%8B%E4%B8%80/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2021/05/12/MM32F103%E4%B8%8A%E5%88%86%E6%9E%90usb%E7%9A%84%E6%9E%9A%E4%B8%BE%E8%BF%87%E7%A8%8B%E4%B8%80/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>​    这里开始分析枚举过程的第一个来回，文章中会具体分析MM32F103相关的USB寄存器含义以及代码，从而更加直观的理解这个过程。</p>
<p>​    枚举过程的第一个来回会发起第一个控制传输：</p>
<ul>
<li>建立过程：主机 SETUP 包（发往地址 0 端点 0 ），主机数据包（请求设备描述符），设备握手包ACK。</li>
<li>数据过程：主机先发一个 IN 令牌包，设备发一个数据包，主机发 ACK 包。</li>
<li>状态过程：主机发 OUT 包（通知设备要输出）、主机发 0 字节状态数据包（这个是 0字节，表明自己收到设备描述符）、设备发握手 ACK 包。</li>
</ul>
<h2 id="1-建立过程"><a href="#1-建立过程" class="headerlink" title="1.建立过程"></a>1.建立过程</h2><p>​    即一个setup事务。<strong>看到事务这两个字，肯定要一下子想到它包含令牌包Token packet、数据包Data packet、握手包Handshack packet</strong>。</p>
<p>​    所以这个setup事务包含有：主机 SETUP 包（发往地址0端点0）、主机数据包（请求设备描述符）、设备握手包ACK 。</p>
<h3 id="1-1-setup事务的setup包"><a href="#1-1-setup事务的setup包" class="headerlink" title="1.1 setup事务的setup包"></a>1.1 setup事务的setup包</h3><p>​    这边主机先发送一个setup包，那么mm32这边会产生一个中断，mm32有一个USB端点0中断状态寄存器(EP0_INT_STATE)</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210427104212.png" style="zoom:67%;">

<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210427104326.png" style="zoom:67%;">

<p>(补充：上面寄存器的说明感觉说的不是特别好，容易引起歧义。更准确的说法我觉得应该是：<strong>置位后可以从寄存器SETUP0~7读取setup事务的数据包内容</strong>)</p>
<p>程序会进入接收到setup包这个中断，如下图所示：</p>
<p><img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/%E5%BE%AE%E4%BF%A1%E6%88%AA%E5%9B%BE_20210427111337.png"></p>
<h3 id="1-2-setup事务的数据包"><a href="#1-2-setup事务的数据包" class="headerlink" title="1.2 setup事务的数据包"></a>1.2 setup事务的数据包</h3><p>​    数据包是主机发送的，用来请求设备的描述符，目的就是告诉设备：我想知道你的设备描述符，这样在后面的数据过程设备就知道要告诉主机什么信息了。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">usb_setup_handle</span><span class="params">( <span class="keyword">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    uint8    temp ;</span><br><span class="line">    <span class="keyword">if</span>(usb_running_ctrl_state == USB_IDLE) </span><br><span class="line">	&#123;</span><br><span class="line">        <span class="comment">//bmrequest type one byte</span></span><br><span class="line">        bmRequestType = USB-&gt;rSETUP[<span class="number">0</span>];<span class="comment">//获取setup事务数据包首字节,记录host请求类型</span></span><br><span class="line">        <span class="comment">//brequest one byte</span></span><br><span class="line">        bRequest = USB-&gt;rSETUP[<span class="number">1</span>];</span><br><span class="line">        </span><br><span class="line">	    <span class="comment">//wvalue two bytes</span></span><br><span class="line">        temp = USB-&gt;rSETUP[<span class="number">2</span>];</span><br><span class="line">        wValue = USB-&gt;rSETUP[<span class="number">3</span>];</span><br><span class="line">        wValue = (wValue &lt;&lt; <span class="number">8</span>) + temp;</span><br><span class="line">        </span><br><span class="line">	   <span class="comment">//windex two bytes</span></span><br><span class="line">        temp = USB-&gt;rSETUP[<span class="number">4</span>];</span><br><span class="line">        wIndex = USB-&gt;rSETUP[<span class="number">5</span>];</span><br><span class="line">        wIndex = (wIndex &lt;&lt; <span class="number">8</span>) + temp;</span><br><span class="line">        </span><br><span class="line">	    <span class="comment">//wlength two bytes</span></span><br><span class="line">        temp = USB-&gt;rSETUP[<span class="number">6</span>];</span><br><span class="line">        wLength = USB-&gt;rSETUP[<span class="number">7</span>];</span><br><span class="line">        wLength = (wLength &lt;&lt; <span class="number">8</span>) + temp;</span><br><span class="line">        <span class="comment">//direction</span></span><br><span class="line">        req_dir = bmRequestType &amp; USB_REQ_DIR_MASK ;</span><br><span class="line">        <span class="comment">//recipient</span></span><br><span class="line">        req_recip = bmRequestType &amp; USB_REQ_RECIP_MASK ;</span><br><span class="line">        <span class="comment">//type</span></span><br><span class="line">        req_type = bmRequestType &amp; USB_REQ_TYPE_MASK ;</span><br><span class="line"><span class="meta">#<span class="meta-keyword">if</span> 0</span></span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;bmRequestType = 0x%x\r\n&quot;</span>, bmRequestType);</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;bRequest = 0x%x\r\n&quot;</span>, bRequest);</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;wValue = 0x%x\r\n&quot;</span>, wValue);</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;wIndex = 0x%x\r\n&quot;</span>, wIndex);</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;wLength = 0x%x\r\n&quot;</span>, wLength);</span><br><span class="line">		<span class="built_in">printf</span>(<span class="string">&quot;=================================\r\n&quot;</span>);</span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span></span></span><br><span class="line">        usb_running_ctrl_state = USB_CTRL_SETUP ;</span><br><span class="line">    &#125;</span><br><span class="line">    ctrl_deal_handle();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>usb_setup_handle函数中，会先读取setup事务数据包里面的内容(从第7行开始)，这就涉及到另外一个寄存器：USB 设置包数据寄存器(SETUPX  (X=0~7))</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210427105459.png" style="zoom:67%;">

<p>(同样这个寄存器名字我感觉取的不是特别好，容易引起歧义。更好的说法我觉得是：USB SETUP事务的数据包寄存器。)</p>
<p>​    usb_setup_handle函数中把setup事务的数据包做解析，数据包肯定是有格式约定的，如下表所示：</p>
<table>
<thead>
<tr>
<th><strong>偏移量</strong></th>
<th><strong>请求</strong></th>
<th><strong>大小</strong></th>
<th><strong>意义</strong></th>
</tr>
</thead>
<tbody><tr>
<td>0</td>
<td>bmRequestType</td>
<td>1</td>
<td>请求命令类型。每一位代表一定的意义。<br>D7，选择数据传输方向，0 = 主机到设备（即输出OUT），1 = 设备到主机（即输入IN）。<br>D6D5，命令的类型<br>00 = 标准请求命令<br>01 = 类请求命令<br>10 = 用户定义的请求命令<br>11 = 保留<br>D4-D0，命令的接收者类型<br>00000 = 接收者为设备<br>00001 = 接收者为接口<br>00010 = 接收者为端点<br>00011 = 其他接收者<br>其他值保留。</td>
</tr>
<tr>
<td>1</td>
<td>bRequest</td>
<td>1</td>
<td>请求命令代码。<br>在标准的USB请求命令中，USB为每一个命令定义了编号，即为此段的值。<br>0 = GET_STATUS<br>1 = CLEAR_FEATURE<br>3 = SET_FEATURE<br>5 = SET_ADDRESS<br>6 = GET_DESCRIPTOR<br>7 = SET_DESCRIPTOR<br>8 = GET_CONFIGURATION<br>9 = SET_CONFIGURATION<br>10 = GET_INTERFACE<br>11 = SET_INTERFACE<br>12 = SYNCH_FRAME</td>
</tr>
<tr>
<td>2</td>
<td>wValue</td>
<td>2</td>
<td>命令信息。<br>每一种请求命令都可以自行来定义这个字段的内容。</td>
</tr>
<tr>
<td>4</td>
<td>wIndex</td>
<td>2</td>
<td>索引信息。<br> 命令也可以自定义该字段的内容，但一般该字段的内容为索引值或偏移值。 当传输一个端点的索引值时： <br>第一字节 D7，方向位，0 = 输出OUT端点，1 = 输入IN端点 <br>D3-D0，端点号 <br>其他位即第二字节为保留值0。<br><br>当传输一个接口的索引值时：<br>第一字节<br>D7~D0，接口编号（可以在接口描述符中得到）<br>第二字节为保留值0。</td>
</tr>
<tr>
<td>6</td>
<td>wLength</td>
<td>2</td>
<td>传输的数据大小。<br>该字段表示在控制传输的“可选数据步骤”中要传输的数据大小。<br>当数据发送方向是主机到设备时，字段值便是实际的数据大小；<br>当数据发送方向是设备到主机时，字段值是设备能够发送的最大数据包的大小<br>当然，设备实际发送的数据可以比wLength的值小。</td>
</tr>
</tbody></table>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/***************************************************************************</span></span><br><span class="line"><span class="comment">**函数信息 ：ctrl_deal_handle(void)</span></span><br><span class="line"><span class="comment">**功能描述 ：控制传输数据包及USB状态处理</span></span><br><span class="line"><span class="comment">**输入参数 ：</span></span><br><span class="line"><span class="comment">**输出参数 ：</span></span><br><span class="line"><span class="comment">**备    注 ：记录USB状态方便USB正确响应</span></span><br><span class="line"><span class="comment">****************************************************************************/</span></span><br><span class="line">u8 usb_flag = <span class="number">0</span>;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">ctrl_deal_handle</span><span class="params">(<span class="keyword">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>( req_type == USB_REQ_TYPE_STANDARD )         <span class="comment">// standard request type</span></span><br><span class="line">		&#123;                   </span><br><span class="line">        <span class="keyword">if</span>( bRequest &lt; MAX_STD_REQUEST )            <span class="comment">// handle 0--12</span></span><br><span class="line">				&#123;                      </span><br><span class="line">            (*StandardDeviceRequest[bRequest])( ) ; <span class="comment">// 调用标准请求函数</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>会解析到是个获取设备描述符标准请求，会转到相应的函数去处理：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210427160420.png" style="zoom:77%;">

<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210427161355.png" style="zoom:80%;">

<p>这边红框处目的就是设备根据主机数据包中的设备描述符请求做好准备，把要回复给主机的设备描述符准备好。</p>
<h3 id="1-3-setup事务的握手包"><a href="#1-3-setup事务的握手包" class="headerlink" title="1.3 setup事务的握手包"></a>1.3 setup事务的握手包</h3><p>​    设备握手包ACK，代码里面没有直接体现。</p>
<br>

<br>

<h2 id="2-数据过程"><a href="#2-数据过程" class="headerlink" title="2. 数据过程"></a>2. 数据过程</h2><p>​    主机先发一个IN令牌包、设备发一个数据包（这个数据已经准备好，SIE收到IN令牌后，直接送到总线上，用户此时不干预）、主机发ACK包。（SIE 指串行接口引擎，是所有USB控制器内部的‘核心’。SIE 负责处理底层协议，如填充位，CRC生成和校验，并可发出错误报告。SIE的主要任务是将低级信号转换成字节，以供控制器使用）</p>
<h3 id="2-1-IN事务的令牌包"><a href="#2-1-IN事务的令牌包" class="headerlink" title="2.1 IN事务的令牌包"></a>2.1 IN事务的令牌包</h3><p>​    主机发送IN事务的令牌包，MCU的端点接收来自主机的IN包后，如果此时没有足够的数据完成当前传输，USB控制器自动应答NACK包，这个会体现在USB端点0中断状态寄存器里面Bit2位：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210506182948.png" style="zoom:77%;">

<p>程序中就体现在下面截图的第75行：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210506183958.png" style="zoom:80%;">

<p>这边程序刚开始运行的时候，肯定是没准备好数据的，所以会到75行这个分支下面。另外有一点：如果收到 NACK 应答，USB主机会重发IN请求直到该端点确认请求有效。</p>
<p>​    现在进入usb_in_handle()函数继续往下分析，按着流程走走走走，竟然又走到了Chap9_GetDescriptor函数，只是跑的是case USB_CTRL_IN这个分支：</p>
<p><img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/%E5%BE%AE%E4%BF%A1%E6%88%AA%E5%9B%BE_20210509135027.png"></p>
<p>这段代码里涉及到两个比较重要的寄存器EPX_CTRL和EPX_FIFO。</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210509140654.png" style="zoom:70%;">

<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210509140822.png" style="zoom:70%;">

<p>​        在 USB 设备的端点描述符中包含了端点最大包长（Max Packet Size 即 MPS）信息。USB的端点一次只能传输最大包长的数据，如果数据超出最大包长，将会分成多包进行传输。多包传输时，前面的数据包长度都是最大包长，只有最后一包数据根据实际长度传输。当要完成一次传输时，发送一个数据长度不是最大包长的数据即</p>
<p>可，有这两种情况：a. 如果数据长度不能最大包长整除，最后一包自然会小于最大包长，触发传输完成条件；b. </p>
<p><strong>如果数据长度能被最大包长整除，最一包与最大包长相等，需要再发送一个长度为零的包（Zero Length Packet）来触发传输完成条件</strong>。代码中294行就很好的说明了这一点。发送长度为零的包代码如下所示：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210510171243.png" style="zoom:80%;">

<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210510152813.png" style="zoom:70%;">

<p>可以总结为下面这样的步骤：</p>
<p>​    1.如果 FIFO 中的数据小于寄存器 EPX_CTRL[6:0] 中设置的大小，或者 EPX_CTRL[7]未设为 1，USB 模块会自动发送 NACK，直到数据准备好。</p>
<p>​    2.CPU 收到 IN_NACK 状态。</p>
<p>​    3.CPU 把数据写入 FIFO。</p>
<p>​    4.CPU 在 EPX_CTRL 寄存器设置待发送的数据大小和发送使能。</p>
<p>​    5.USB 模块在收到下一个 IN 请求的时候自动发送 FIFO 中的数据发送。最后一个数据字节发送完成后，自动发送计算好的 CRC。</p>
<p>​    6.CPU 会收到 IN_ACK 状态，并且在发送结束后收到 END 状态。</p>
<p>​    7.如果端点未使能，或者 EP_HALT 寄存器设置暂停，USB模块会应答IN_STALL而不发送数据。</p>
<h3 id="2-2-IN事务的数据包"><a href="#2-2-IN事务的数据包" class="headerlink" title="2.2 IN事务的数据包"></a>2.2 IN事务的数据包</h3><p>​    体现在上面的步骤5中，设备会给主机返回18字节的设备描述符。</p>
<h3 id="2-3-IN事务的握手包"><a href="#2-3-IN事务的握手包" class="headerlink" title="2.3 IN事务的握手包"></a>2.3 IN事务的握手包</h3><p>​    主机发送ACK包，代码里面没有直接体现。</p>
<br>

<br>

<h2 id="3-状态过程"><a href="#3-状态过程" class="headerlink" title="3. 状态过程"></a>3. 状态过程</h2><p>​    主机发 OUT 包（通知设备要输出）、主机发 0 字节状态数据包（这个是 0字节，表明自己收到设备描述符）、设备发握手 ACK 包。</p>
<p>​    设备接收到主机OUT包的代码应该在如下所示地方：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/微信截图_20210512144107.png" style="zoom:67%;">

<p>状态过程的数据包和握手包这边没具体看到有相应的代码，暂时不做具体的分析了。</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/USB%E5%9F%BA%E7%A1%80/" rel="tag"># USB基础</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/05/04/Jetson%20nano%20i2c/" rel="prev" title="Jetson nano i2c">
      <i class="fa fa-chevron-left"></i> Jetson nano i2c
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/05/16/Jetson%20Nano%E9%80%9A%E8%BF%87%E7%AC%94%E8%AE%B0%E6%9C%AC%E5%AE%9E%E7%8E%B0%E7%BD%91%E7%BB%9C%E8%BF%9E%E6%8E%A5/" rel="next" title="Jetson Nano通过笔记本实现网络连接">
      Jetson Nano通过笔记本实现网络连接 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E5%BB%BA%E7%AB%8B%E8%BF%87%E7%A8%8B"><span class="nav-number">1.</span> <span class="nav-text">1.建立过程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-setup%E4%BA%8B%E5%8A%A1%E7%9A%84setup%E5%8C%85"><span class="nav-number">1.1.</span> <span class="nav-text">1.1 setup事务的setup包</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-setup%E4%BA%8B%E5%8A%A1%E7%9A%84%E6%95%B0%E6%8D%AE%E5%8C%85"><span class="nav-number">1.2.</span> <span class="nav-text">1.2 setup事务的数据包</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-setup%E4%BA%8B%E5%8A%A1%E7%9A%84%E6%8F%A1%E6%89%8B%E5%8C%85"><span class="nav-number">1.3.</span> <span class="nav-text">1.3 setup事务的握手包</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E6%95%B0%E6%8D%AE%E8%BF%87%E7%A8%8B"><span class="nav-number">2.</span> <span class="nav-text">2. 数据过程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-IN%E4%BA%8B%E5%8A%A1%E7%9A%84%E4%BB%A4%E7%89%8C%E5%8C%85"><span class="nav-number">2.1.</span> <span class="nav-text">2.1 IN事务的令牌包</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-IN%E4%BA%8B%E5%8A%A1%E7%9A%84%E6%95%B0%E6%8D%AE%E5%8C%85"><span class="nav-number">2.2.</span> <span class="nav-text">2.2 IN事务的数据包</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-IN%E4%BA%8B%E5%8A%A1%E7%9A%84%E6%8F%A1%E6%89%8B%E5%8C%85"><span class="nav-number">2.3.</span> <span class="nav-text">2.3 IN事务的握手包</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E7%8A%B6%E6%80%81%E8%BF%87%E7%A8%8B"><span class="nav-number">3.</span> <span class="nav-text">3. 状态过程</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">xudonglei</p>
  <div class="site-description" itemprop="description">搬砖 嵌入式</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">283</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">19</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">67</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xudonglei</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'BT0Qw9HcTpPv1a6cT1iDBXKz-gzGzoHsz',
      appKey     : 'LMCMh8v02JTMFAwKNRcgoizI',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : true,
      lang       : 'zh-CN' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
